/**
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 */
package com.jeesite.modules.kj.web;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONValidator;
import com.jeesite.common.codec.EncodeUtils;
import com.jeesite.common.config.Global;
import com.jeesite.common.entity.Page;
import com.jeesite.common.lang.DateUtils;
import com.jeesite.common.lang.StringUtils;
import com.jeesite.common.utils.excel.ExcelExport;
import com.jeesite.common.web.BaseController;
import com.jeesite.modules.aliyun.msg.AliyunSmsUtils;
import com.jeesite.modules.kj.dao.KjActivityCommentDao;
import com.jeesite.modules.kj.entity.*;
import com.jeesite.modules.kj.enums.IntegralEnum;
import com.jeesite.modules.kj.service.*;
import com.jeesite.modules.kj.utils.IntegralUtil;
import com.jeesite.modules.kj.utils.SystemLogUtil;
import com.jeesite.modules.sys.entity.Log;
import com.jeesite.modules.sys.utils.UserUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.stream.Collectors;

/**
 * kj_activityController
 * @author hzy
 * @version 2021-07-06
 */
@Controller
@RequestMapping(value = "${adminPath}/kj/kjActivity")
public class KjActivityController extends BaseController {

	@Autowired
	private KjActivityService kjActivityService;

	@Autowired
	private KjActivityJobService kjActivityJobService;
	@Autowired
	private KjMemberJobService kjMemberJobService;
	@Autowired
	private KjJobTypeService kjJobTypeService;
	@Value("${msg.sms.template.lovePointsArrive}")
	private String lovePointsArrive;

	@Autowired
	KjActivityCommentDao kjActivityCommentDao;

	@Autowired
	KjActivityCommentService kjActivityCommentService;

	/**
	 * 获取数据
	 */
	@ModelAttribute
	public KjActivity get(String id, boolean isNewRecord) {
		return kjActivityService.get(id, isNewRecord);
	}

	/**
	 * 查询列表
	 */
	@RequiresPermissions("kj:kjActivity:view")
	@RequestMapping(value = {"list", ""})
	public String list(KjActivity kjActivity, Model model) {
		model.addAttribute("kjActivity", kjActivity);
		return "modules/kj/kjActivityList";
	}

	/**
	 * 查询列表数据
	 */
	@RequiresPermissions("kj:kjActivity:view")
	@RequestMapping(value = "listData")
	@ResponseBody
	public Page<KjActivity> listData(KjActivity kjActivity, HttpServletRequest request, HttpServletResponse response) {
		kjActivity.setPage(new Page<>(request, response));
		Page<KjActivity> page = kjActivityService.findPage(kjActivity);
		return page;
	}

	/**
	 * 查看编辑表单
	 */
	@RequiresPermissions("kj:kjActivity:view")
	@RequestMapping(value = "form")
	public String form(KjActivity kjActivity,String action, Model model) {
		if(StringUtils.isNotBlank(kjActivity.getId())){
			KjActivityJob where = new KjActivityJob();
			where.setActivityId(kjActivity.getId());
			List<KjActivityJob> kjActivityJobList = kjActivityJobService.findList(where);
			kjActivity.setActivityJobList(kjActivityJobList);
		}
		List<KjJobType> jobTypes = kjJobTypeService.findList(new KjJobType());
		List<JSONObject> typeMap = new ArrayList<>();
		for (KjJobType type: jobTypes
			 ) {
			typeMap.add((JSONObject)JSONObject.toJSON(type));
		}
		model.addAttribute("jobTypes", typeMap);
		model.addAttribute("kjActivity", kjActivity);
		model.addAttribute("action",action);
		return "modules/kj/kjActivityForm";
	}

	/**
	 * 保存数据
	 */
	@RequiresPermissions("kj:kjActivity:edit")
	@PostMapping(value = "save")
	@ResponseBody
	public String save(@Validated KjActivity kjActivity, HttpServletRequest request) {
		String validData = kjActivityService.validDate(kjActivity);
		if(validData != null){
			return renderResult(Global.FALSE, validData);
		}
		//修改之后应该重新进行审核
		kjActivity.setActivityAudit("0");
		if(UserUtils.getUser().toString().equals("system") || UserUtils.getSubject().isPermitted("kj:kjActivity:audit")){
			kjActivity.setActivityAudit("1");
		}
		//用空字符串代替数据
		kjActivity.setRemarks("");
		//
		if(StringUtils.isNotBlank(kjActivity.getId())) {
			KjActivity oldActivity = kjActivityService.get(kjActivity.getId());
			if(StringUtils.isBlank(oldActivity.getGroupQrcode()) && StringUtils.isNotBlank(kjActivity.getGroupQrcode())){
				kjActivityService.sendQrcodeUploadSms(kjActivity);
				SystemLogUtil.insertAdminOperate(UserUtils.getUser(), "上传入群二维码", Log.TYPE_UPDATE, "上传入群二维码", kjActivity.getName(), request);
			}
		}else{
			SystemLogUtil.insertAdminOperate(UserUtils.getUser(), "活动管理", Log.TYPE_UPDATE, "创建活动", kjActivity.getName(), request);
		}
		if(kjActivity.getId()!=null && !kjActivity.getId().equals("")) {
			//实现更新kjmemberjob里面的数据
			this.editMemberJob(kjActivity);
			//更新活动评论
			this.editActivityComment(kjActivity);
		}
		kjActivityService.saveForm(kjActivity);
		return renderResult(Global.TRUE, text("保存活动成功！"));
	}

	/**
	 * 审核数据
	 */
	@RequiresPermissions("kj:kjActivity:audit")
	@PostMapping(value = "audit")
	@ResponseBody
	public String audit(@Validated KjActivity kjActivity, String action, HttpServletRequest request) {
		String validData = kjActivityService.validDate(kjActivity);
		if(validData != null){
			return renderResult(Global.FALSE, validData);
		}
		//
		String audit="";
		if(action.equals("submit")){
           kjActivity.setActivityAudit("1");
           audit="已通过活动审核！";
           //kjActivity.setRemarks(null);
		}else if(action.equals("reject")){
			kjActivity.setActivityAudit("2");
			audit="已拒绝活动审核！";
		}else {
			return renderResult(Global.FALSE, text("未包含审核结果"));
		}
		if(StringUtils.isNotBlank(kjActivity.getId())) {
			KjActivity oldActivity = kjActivityService.get(kjActivity.getId());
			if(StringUtils.isBlank(oldActivity.getGroupQrcode()) && StringUtils.isNotBlank(kjActivity.getGroupQrcode())){
				//kjActivityService.sendQrcodeUploadSms(kjActivity);
				SystemLogUtil.insertAdminOperate(UserUtils.getUser(), "上传入群二维码", Log.TYPE_UPDATE, "上传入群二维码", kjActivity.getName(), request);
			}
		}else{
			SystemLogUtil.insertAdminOperate(UserUtils.getUser(), "活动管理", Log.TYPE_UPDATE, "修改活动", kjActivity.getName(), request);
		}
		kjActivityService.saveForm(kjActivity);
		return renderResult(Global.TRUE, text(audit));
	}

	/**
	 * 删除数据
	 */
	@RequiresPermissions("kj:kjActivity:edit")
	@RequestMapping(value = "delete")
	@ResponseBody
	public String delete(KjActivity kjActivity, HttpServletRequest request) {
		SystemLogUtil.insertAdminOperate(UserUtils.getUser(), "活动管理", Log.TYPE_UPDATE, "删除活动", kjActivity.getName(), request);
		kjActivityCommentDao.del(kjActivity.getId());

		kjActivityService.delete(kjActivity);
		KjActivityJob where = new KjActivityJob();
		where.setActivityId(kjActivity.getId());
		List<KjActivityJob> activityJobList = kjActivityJobService.findList(where);
		for (KjActivityJob aj: activityJobList
		) {
			kjActivityJobService.delete(aj);
			KjMemberJob mjWhere = new KjMemberJob();
			mjWhere.setActivityId(kjActivity.getId());
			mjWhere.setApproveStatus(KjMemberJob.OK);
			List<KjMemberJob> memberJobList = kjMemberJobService.findList(mjWhere);
			for (KjMemberJob mj: memberJobList
			) {
				kjMemberJobService.delete(mj);
				if(KjMemberJob.SENDED.equals(mj.getSendStatus())){
					IntegralUtil.addIntegrals(mj.getKjMember(), mj.getId(), aj.getJobTypeId(), IntegralEnum.DELACTIVITY, mj.getIntegrals().negate(), mj.getServiceTime().negate(), mj.getActivityName());
				}
			}
		}
		return renderResult(Global.TRUE, text("删除活动成功！"));
	}

	/**
	 * 列表选择对话框
	 */
	@RequiresPermissions("kj:kjActivity:view")
	@RequestMapping(value = "kjActivitySelect")
	public String empUserSelect(KjActivity kjActivity, String selectData, Model model) {
		String selectDataJson = EncodeUtils.decodeUrl(selectData);
		if (selectDataJson != null && JSONValidator.from(selectDataJson).validate()){
			model.addAttribute("selectData", selectDataJson);
		}
		model.addAttribute("KjActivity", kjActivity);
		return "modules/kj/kjActivitySelect";
	}



	/**
	 * 保存数据
	 */
	@RequiresPermissions("kj:kjActivity:edit")
	@PostMapping(value = "copy")
	@ResponseBody
	public String copy(@Validated KjActivity kjActivity, HttpServletRequest request) {
		kjActivity=kjActivityService.get(kjActivity);
		if(StringUtils.isNotBlank(kjActivity.getId())){
			KjActivityJob where = new KjActivityJob();
			where.setActivityId(kjActivity.getId());
			List<KjActivityJob> kjActivityJobList = kjActivityJobService.findList(where);
			kjActivityJobList=kjActivityJobList.stream().map(e->{
				e.setActivityId(null);
				e.setId(null);
				e.setActivityName(null);
				e.setApprovedNum(0L);
				e.setAttentionNum(0L);
				return e;
			}).collect(Collectors.toList());
			kjActivity.setActivityJobList(kjActivityJobList);
		}
		SystemLogUtil.insertAdminOperate(UserUtils.getUser(), "活动管理", Log.TYPE_UPDATE, "复制了一条数据", kjActivity.getName(), request);
		kjActivity.setId(null);
		kjActivity.setRemarks("");
		//删除的活动进行复制，放入正常数据中
		kjActivity.setStatus("0");
		kjActivity.setName("(复制)" + kjActivity.getName() );
		//复制时其审核状态应该为0
		kjActivity.setActivityAudit("0");
		kjActivityService.saveForm(kjActivity);
		return renderResult(Global.TRUE, text("复制活动成功！"));
	}


	/**
	 * 批量发放积分
	 */
	@RequiresPermissions("kj:kjActivity:edit")
	@PostMapping(value = "batchAddIntegral")
	@ResponseBody
	public String batchAddIntegral(KjActivity kjActivity) {
		Set<String> set=new HashSet<>();
		KjActivityJob where = new KjActivityJob();
		where.setActivityId(kjActivity.getId());
		List<KjActivityJob> activityJobList = kjActivityJobService.findList(where);
		for (KjActivityJob aj: activityJobList
			 ) {
			KjMemberJob mjWhere = new KjMemberJob();
			mjWhere.setJobId(aj.getId());
			mjWhere.setApproveStatus(KjMemberJob.OK);
			List<KjMemberJob> memberJobList = kjMemberJobService.findList(mjWhere);
			for (KjMemberJob mj: memberJobList
				 ) {
				if(!KjMemberJob.SENDED.equals(mj.getSendStatus())){
					IntegralUtil.addIntegrals(mj.getKjMember(), mj.getId(), aj.getJobTypeId(), IntegralEnum.ACTIVITY, aj.getIntegrals(), aj.getServiceTime(), aj.getActivityName());
					mj.setSendStatus(KjMemberJob.SENDED);
					mj.setIntegrals(aj.getIntegrals());
					mj.setServiceTime(aj.getServiceTime());
					set.add(mj.getKjMember().getMobile());
					//AliyunSmsUtils.sendMessages(mj.getKjMember().getMobile(),lovePointsArrive,new HashMap<>());
					kjMemberJobService.save(mj);
				}
			}
		}
		List<String> mobiles=new ArrayList<>(set);
		for(String mobile : mobiles){
			AliyunSmsUtils.sendMessages(mobile,lovePointsArrive,new HashMap<>());
		}
		return renderResult(Global.TRUE, text("积分发放成功！"));
	}


	/**
	 * 导出活动数据
	 */
	@RequiresPermissions("kj:kjActivity:view")
	@RequestMapping(value = "exportData")
	public void exportData(KjActivity kjActivity, Boolean isAll, String ctrlPermi, HttpServletResponse response) {
		kjActivity.setPageNo(null);
		kjActivity.setPageSize(null);
		List<KjActivity> list = kjActivityService.findList(kjActivity);
		String fileName = "活动数据" + DateUtils.getDate("yyyyMMddHHmmss") + ".xlsx";
		try(ExcelExport ee = new ExcelExport("活动数据", KjActivity.class)){
			ee.setDataList(list).write(response, fileName);
		}
	}



    //同步修改活动评论
	private void editActivityComment(KjActivity kjActivity) {
		KjActivity kjActivity1=new KjActivity();
		BeanUtils.copyProperties(kjActivity,kjActivity1);
		new Thread(()->{
			KjActivityComment comment=new KjActivityComment();
			comment.setActivityId(kjActivity1.getId());
			List<KjActivityComment> list;
			synchronized(this) {
				list = kjActivityCommentDao.findList(comment);
			}
			for(KjActivityComment activityComment: list){
				activityComment.setActivityName(kjActivity1.getName());
				kjActivityCommentService.save(activityComment);
			}
		}).start();
	}

	//同步修改报名数据
	public void editMemberJob(KjActivity kjActivity){
		KjActivity kjActivity1=new KjActivity();
		BeanUtils.copyProperties(kjActivity,kjActivity1);
		new Thread(()->{
			KjMemberJob job=new KjMemberJob();
			job.setActivityId(kjActivity1.getId());
			List<KjMemberJob> list;
			synchronized(this) {
				list = kjMemberJobService.findList(job);
			}
			for(KjMemberJob kjMemberJob: list){
				kjMemberJob.setActivityName(kjActivity1.getName());
				kjMemberJobService.save(kjMemberJob);
			}
		}).start();
	}

}
